package org.budo.support.spring.security.authentication.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

/**
 * Authorization: Basic MToy
 * 
 * @see org.springframework.security.web.authentication.www.BasicAuthenticationConverter#convert(HttpServletRequest)
 */
public class AuthenticationUtil {
    public static String[] usernamePassword(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header == null) {
            return null;
        }

        header = header.trim();
        if (!StringUtils.startsWithIgnoreCase(header, "Basic")) {
            return null;
        }

        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("#91 Failed to decode basic authentication token");
        }

        String token = new String(decoded, StandardCharsets.UTF_8);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new RuntimeException("Invalid basic authentication token");
        }

        String username = token.substring(0, delim);
        String password = token.substring(delim + 1);

        return new String[] { username, password };
    }
}
